package com.Education.util;

import com.Education.pojo.Course;
import com.Education.pojo.Schedule;
import com.Education.pojo.User;
import com.Education.server.Impl.UserServiceImpl;
import com.Education.server.ScheduleService;
import com.Education.server.UserService;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class HttpObtainSchedule {

    @Autowired
    UserService userService;

    @Autowired
    ScheduleService scheduleService;

    public static HttpObtainSchedule httpObtainSchedule;    //将自己作为静态私有变量引入，使其在spring初始化前就被创建

    @PostConstruct              //通过@PostConstruct和@PreDestroy方法，实现初始化和销毁bean之前的操作
    public void init(){
        httpObtainSchedule = this;
    }

    public static Object obtainSchedule(User user,String grade, String semester) throws IOException {

        System.out.println("来了obtainSchedule");

        //构建课程表的id名称
        String id = user.getUsername()+grade+semester;

        Object object = new Object();

        /*
        //获取连接客户端工具(创建httpClient实例)，(创建cookieStore实例)
        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie1 = new BasicClientCookie("JSESSIONID", user.getJSESSIONID());
        cookie1.setDomain("jw.jluzh.edu.cn");
        cookie1.setPath("/");
        cookieStore.addCookie(cookie1);
        BasicClientCookie cookie2 = new BasicClientCookie("route", user.getRoute());
        cookie2.setDomain("jw.jluzh.edu.cn");
        cookie2.setPath("/");
        cookieStore.addCookie(cookie2);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();

         */


        //初始化
        HttpClientSession httpClientSession = HttpClientUtils.getHttpClient(user.getUsername());
        CloseableHttpClient httpClient = httpClientSession.getCloseableHttpClient();
        CookieStore cookieStore = httpClientSession.getCookieStore();

        String loginurl = "http://jw.jluzh.edu.cn/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151";
        //设置参数
        //3.设置参数
        List<NameValuePair> parameters3 = new ArrayList<NameValuePair>(0);
        parameters3.add(new BasicNameValuePair("xnm", grade));  //年级
        parameters3.add(new BasicNameValuePair("xqm", semester));   //学期

        //声明post请求
        HttpPostUtils httpPostUtils = new HttpPostUtils();
        HttpPost httpPost = httpPostUtils.post(loginurl,parameters3);

        //5.发送请求，返回内容
        CloseableHttpResponse response = httpClient.execute(httpPost);

        //int statusCode = response.getStatusLine().getStatusCode();


        if(response.getStatusLine().getStatusCode() == 200){
            HttpEntity entity3 = response.getEntity();
            String result = EntityUtils.toString(entity3, "utf-8");
            if(result != null){
                //JSONObject jsonObject = JSONObject.parseObject(result);
                //Map<Object, Object> result2 = jsonToMap(jsonObject);
                Map<String, Object> result2 = jsonToMap(result);

                //保存或更新课程表
                Schedule schedule = new Schedule();
                schedule.setId(id);
                schedule.setScheduleMap(result2);

                Schedule schedule2 =httpObtainSchedule.scheduleService.querySchedule(id);
                if (schedule2 == null){
                    httpObtainSchedule.scheduleService.saveSchedule(schedule);
                }else {
                    httpObtainSchedule.scheduleService.updateSchedule(schedule);
                }


                //System.out.println("1"+jsonObject.getString("kbList"));
                //json格式化输出
                //ObjectMapper mapper = new ObjectMapper();
                //System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject));

                //List kbList = (List) jsonObject.get("kbList");
                List<Course> courseList = courseList(result2);

                object = courseList;

            }

        }else if(response.getStatusLine().getStatusCode() == 302){

            System.out.println("302");

            //重新登录
            User userResult = HttpLoginEduUtil.loginEdu(user);

            if(userResult != null) {
                httpObtainSchedule.userService.updateUserJseRou(userResult);
            }


            object = 302;
        }


        //关闭资源
        response.close();
        httpClient.close();

        return object;

    }


    /**
     * json string 转换为 map 对象
     * @param result2
     * @return
     */
    public static List courseList(Map<String, Object> result2){

        List kbList = (List) result2.get("kbList");

        List<Course> courseList = new ArrayList<>();

        for (int i = 0; i<kbList.size();i++){

            Map<String, Object> result3 = jsonToMap(kbList.get(i));

            List weekList = parseZcd(result3.get("zcd")+"");
            Integer[] integers = parseJcs(result3.get("jcs")+"");
            Integer skjc = integers[0];
            Integer skcd = integers[1];

            Course course = new Course();
            course.setJc(result3.get("jc")+"");
            course.setJcs(result3.get("jcs")+"");
            course.setZcd(result3.get("zcd")+"");
            course.setKcmc(result3.get("kcmc")+"");
            course.setXf(result3.get("xf")+"");
            course.setXm(result3.get("xm")+"");
            course.setZcmc(result3.get("zcmc")+"");
            course.setCdmc(result3.get("cdmc")+"");
            course.setCd_id(result3.get("cd_id")+"");
            course.setXqj(result3.get("xqj")+"");
            course.setWeeklist(weekList);
            course.setSkjc(skjc);
            course.setSkcd(skcd);

            courseList.add(course);
        }

        return courseList;
    }


    /**
     * json string 转换为 map 对象
     * @param jsonObj
     * @return
     */
    public static Map<String, Object> jsonToMap(Object jsonObj) {
        JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
        Map<String, Object> map = (Map)jsonObject;
        return map;
    }

    /*
     * “1-4周,6-16周”转化为具体周的List
     * @param str
     * @return
    */
    public static List parseZcd(String str){
        //切割类型：“1-4周,6-16周”，“3周,6-16周”，“3周”，“1-15周”，“1-15周(单)”，“1-4周,6-16周‘双’，“1-9周(单),13-15周(单)”
        //String str = "1-9周(单),13-15周(单)";
        List weeklist = new ArrayList();    //存放1-4周,6-16周中的周数
        String[] strs=str.split(",");   //如果有逗号，以逗号为切割点切割

        //切割后的数据类型：1-4周，3周，1-15周(单)，6-16周(双)
        for(int i=0,len=strs.length;i<len;i++){

            //strs[i] = strs[i].substring(0, strs[i].length() -1);    //除去“周”字
            String remove = "周";
            strs[i] = strs[i].replace(remove,""); //除去“周”字

            //判断去周后是否为纯数字：3
            if(!strs[i].contains("-")){
                //System.out.println("不存在：'-'");
                weeklist.add(Integer.parseInt(strs[i]));
            }else if(strs[i].contains("单")){    //判断是否为单周

                //System.out.println("存在：'单'");

                String singleweek = "(单)";
                strs[i] = strs[i].replace(singleweek,""); //除去“(单)”字

                String[] singleweeks=strs[i].split("-");

                //遍历切割后的字段，如：1 13，获取其中的周数，添加到集合中
                for(int singleStr = Integer.parseInt(singleweeks[0]); singleStr<=Integer.parseInt(singleweeks[1]); singleStr=singleStr+2){
                    //System.out.print(singleStr+" ");
                    weeklist.add(singleStr);
                }
            }else if(strs[i].contains("双")){    //判断是否为双周

                //System.out.println("存在：'双'");

                String doubleweek = "(双)";
                strs[i] = strs[i].replace(doubleweek,""); //除去“(双)”字

                String[] doubleweeks=strs[i].split("-");

                //遍历切割后的字段，如：1 13，获取其中的周数，添加到集合中
                for(int doubleStr = Integer.parseInt(doubleweeks[0]); doubleStr<=Integer.parseInt(doubleweeks[1]); doubleStr=doubleStr+2){
                    //System.out.print(doubleStr+" ");
                    weeklist.add(doubleStr);
                }
            }else {
                String[] strs2=strs[i].split("-");  //把切割后的字段再以“-”切割
                //遍历切割后的字段，如：1 13，获取其中的周数，添加到集合中
                for(int j = Integer.parseInt(strs2[0]); j<=Integer.parseInt(strs2[1]); j++){
                    weeklist.add(j);
                }
            }
            //System.out.println();
        }
        //System.out.println("weeklist:"+weeklist);
        return weeklist;
    }


    /*
     * “"7-8"转化为具体上课第几节和上课长度的Integer[]
     * @param str
     * @return
     */
    public static Integer[] parseJcs(String str){

        Integer[] integers = new Integer[2];

        //String jsc = "7-8";
        //String str = "7-8";
        String[] strs=str.split("-");
//        for(int i=0,len=strs.length;i<len;i++){
//            System.out.print(strs[i]+" ");
//        }
        //System.out.println();

        //skjc代表第几节，skcd表示上课长度
        int skjc = Integer.parseInt(strs[0]);
        int a = Integer.parseInt(strs[1]);
        int skcd = a - skjc + 1;

        //System.out.println("skjc:"+skjc+" "+"skcd:"+skcd);
        integers[0] = skjc;
        integers[1] = skcd;

        return integers;
    }

}
